#!/usr/bin/env python

import sys, os, os.path, time
from xml.dom.minidom import parse

def pr_red_info(message):
	print "\033[31m%s\033[0m" % message

def pr_green_info(message):
	print "\033[32m%s\033[0m" % message

def pr_bold_info(message):
	print "\033[1m%s\033[0m" % message

def show_usage():
	pr_bold_info("%s command" % os.path.basename(sys.argv[0]))

def execute_repo_command(command_raw):
	root_path = os.path.abspath(".")
	os.chdir(os.path.join(root_path, ".repo/manifests"))
	os.system("git pull")
	dom = parse(os.path.join(root_path, ".repo/manifest.xml"))
	tagManifest = dom.getElementsByTagName("manifest").item(0)
	for project in tagManifest.getElementsByTagName("project"):
		path = project.getAttribute("path")
		name = project.getAttribute("name")
		command = command_raw.replace("<path>", path).replace("<name>", name)
		abs_path = os.path.join(root_path, path)
		pr_bold_info("%s <= \"%s\"" % (path, command))
		os.chdir(abs_path)
		if os.system(command) != 0:
			return -1
	return 0

if __name__ == "__main__":
	if len(sys.argv) < 2:
		date = time.localtime(time.time())
		filename = "%d%02d%d%d%02d%02d.diff" % (date[0], date[1], date[2], date[3], date[4], date[5])
		command = "git diff > %s && git reset --hard && git pull" % filename
	else:
		command = " ".join(sys.argv[1:])

	if execute_repo_command(command) < 0:
		pr_red_info("Failed")
	else:
		pr_green_info("OK")
